<template>
  <div>
    <el-dialog v-model="treeStore.directoryDialogVModel" title="目录浏览" width="500" style="min-height: 580px"
               :center="true" :close-on-click-modal="false">
      <template v-if="treeStore.directoryDialogVModel">
        <el-tree ref="treeRef" :props="directoryProps" :load="loadNode" :check-on-click-node="false" :empty-text="emptyText"
                 node-key="path" :check-strictly="true" @check="handleClick" lazy show-checkbox/>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFn"> 确认</el-button>
          <el-button @click="cleanTree">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive} from "vue";
import {
  req_getDirectorys,
  req_getRegistryDirs,
  req_getProtectDir
} from "~/utils/axios/common.js";
import {useTreeStore} from "~/utils/pinia/tree.js";
import {ElMessage} from "element-plus";
import { useRouter } from "vue-router";

// 内容为空的时候展示的数据，由于是懒加载，在初始化的时候会展示无数据
const emptyText = ref('加载中...')
const treeStore = useTreeStore();
const treeRef = ref();
const directoryProps = {
  label: "name",
  children: "dir",
  isLeaf: 'leaf'
};
const props = defineProps({
  // 0:全部目录 1:防护目录 2:注册表目录
  urlType: {
    type: Number,
    default: 0,
  },
  // 可以勾选的类型，false 是选择文件， true 是选择文件夹
  dirFlag: {
    type: Boolean,
    default: false,
  },
  // 判断是否多选
  multipleChoice: {
    type: Boolean,
    default: false,
  },
  // 文件类型限制
  typeRestrictions: {
    type: Array,
    default: []
  },
  // 根目录是否可选择，例如C盘和D盘是否可选中，默认不可选中
  rootDirFlag: {
    type: Boolean,
    default: false,
  },
  // 操作系统类型，0 是windows， 1 是 linux
  os: {
    type: String,
    default: "win",
  }
});
// const treeData = reactive([]);
let path
let protectDir = ref()
let $router = useRouter();
// let treeNodeId = 0;
// const thisNode = ref(null);
// 部门树形组件 懒加载数据获取函数
const loadNode = (node, resolve) => {
  if (!treeStore.treeDeviceId) {
    return;
  }
  let pathUrl = '/';
  if (node.level === 0) {
    path = props.urlType === 2 ? "" : "/"
  } else {
    path = node.data.path
  }
  let arr = [];
  const getParentPath = (parent) => {
    if (parent.parent.data.name) {
      getParentPath(parent.parent);
    }
    arr.push(parent.data.name);
  };
  if (node.data.name) {
    getParentPath(node);
    if (props.os == "win") {
      pathUrl = arr[0] + arr.slice(1).join("\\");
      console.log("pathUrl :" + pathUrl)
    } else {
      pathUrl = "/" + arr.join("/");
      console.log("pathUrl :" + pathUrl)
    }
  }
  let listNode = [];
  if (props.urlType === 2) {
    // 获取注册表目录
    req_getRegistryDirs(treeStore.treeDeviceId, {path}).then((res) => {
      if (res.data.list) {
        res.data.list.map((item) => {
          listNode.push({
            name: item,
            path: node.level === 0 ? item : path + "\\" + item,
            disabled: node.level === 0 ? true : false,
          });
        });
      }
      listNode.length >= 1 ? resolve(listNode) : resolve([]);
    });
  } else {
    req_getDirectorys(treeStore.treeDeviceId, {
      path: pathUrl,
      type: props.urlType,
    }).then( async (res) => {
      if($router.currentRoute.value.path === '/file'){
        protectDir.value = await req_getProtectDir(treeStore.treeDeviceId)
      }
      // $router.currentRoute.value.path
      console.log($router.currentRoute.value.path)
      let fileLists = res.data.fileLists || [];
      for (let i = 0; i < fileLists.length; i++) {
        // 如果是只能选择文件夹,就不加载type为 file 的
        if (props.dirFlag && fileLists[i].type == "file") {
          continue;
        }
        if (props.typeRestrictions.length != 0) {
          // 文件类型设置
          if (props.typeRestrictions && fileLists[i].type != 'dir' && !props.dirFlag && !props.typeRestrictions.includes(fileLists[i].name.split('.')[fileLists[i].name.split('.').length - 1])) {
            continue
          }
        }
        
        if (props.os == "win") {
          listNode.push({
            ...fileLists[i],
            path: node.level === 0 ? fileLists[i].name : node.level === 1 ? path + fileLists[i].name : path + "\\" + fileLists[i].name,
            disabled: fileLists[i].type == "file" || props.dirFlag ? ((node.level === 0 && !props.rootDirFlag) ? true : false) : true,
            leaf: fileLists[i].type == "file" ? true : false
          });
        } else {
          if(protectDir.value?.data?.list?.length > 0){
            listNode.push({
              ...fileLists[i],
              path: node.level === 0 ? "/" + fileLists[i].name : path + "/" + fileLists[i].name,
              disabled: protectDir.value.data.list.map(item => item.path).includes(node.level === 0 ? "/" + fileLists[i].name : path + "/" + fileLists[i].name),
              leaf: fileLists[i].type == "file" ? true : false
            });
          }else{
            listNode.push({
              ...fileLists[i],
              path: node.level === 0 ? "/" + fileLists[i].name : path + "/" + fileLists[i].name,
              disabled: fileLists[i].type == "file" || props.dirFlag ? ((node.level === 0 && !props.rootDirFlag) ? true : false) : true,
              leaf: fileLists[i].type == "file" ? true : false
            });
          }
        }
      }
      if (listNode.length > 0) {
        resolve(listNode);
      } else {
        resolve([]);
        emptyText.value = '无数据'
      }
    });
  }
};
let checkPath = null
const handleClick = (data, tree) => {
  if (props.multipleChoice) {
    // 多选
    checkPath = treeRef.value.getCheckedNodes().map(item => {
      return item.path
    })
  } else {
    // 单选
    treeRef.value.setCheckedKeys([]); // 删除所有选中节点
    treeRef.value.setCheckedNodes([data]); // 选中已选中节点
    checkPath = treeRef.value.getCheckedNodes()[0].path
  }
};
const cleanTree = () => {
  treeStore.directoryDialogVModel = false;
  path = props.urlType === 2 ? "" : "/"
  checkPath = null
};
const emit = defineEmits(["handleDialogButton"]);
const submitFn = () => {
  // let paramsPath = path == "/" ? "" : decodeURIComponent(path).split(/\\\\/g).filter((item) => item !== "").join("\\");
  // let paramsPathArr = []
  // if(!props.multipleChoice){
  //     if (props.dirFlag) {
  //         if(paramsPath.split(/\\/g)[paramsPath.split(/\\/g).length-1] != thisNode.value.name){
  //             paramsPath += "\\" + thisNode.value.name;
  //         }
  //     }else{
  //         paramsPath += "\\" + thisNode.value.name;
  //     }
  // }else{
  //     thisNode.value.map(checkItem => {
  //         paramsPathArr.push(paramsPath + "\\" + checkItem.name)
  //     })
  // }
  if (!checkPath) {
    ElMessage.error("请选择目录或文件");
    return;
  }
  emit("handleDialogButton", treeRef, checkPath);
  cleanTree();
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog) {
  .el-tree{
    height: 460px;
    overflow-y: auto;
  }
}
</style>